import os
import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import models.vehicle as vehicle

class Home(webapp.RequestHandler):
  def get(self, more=None):
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      nickname = users.get_current_user().nickname()
      v = vehicle.Vehicle.all()
      v.filter("owner =", users.get_current_user())
      v.order("make")
      results = v.fetch(100)
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'nickname' : nickname,
      'results' : results,
      'url': url,
      'url_linktext': url_linktext
      }
    path = os.path.join(os.path.dirname(__file__), '../views/home.html')
    self.response.out.write(template.render(path, template_values))

  def post(self, vid=None):
    v = vehicle.Vehicle.get_by_id(int(vid))
    v.delete()
    self.redirect("/home")


class AddVehicle(webapp.RequestHandler):
    def get(self, vid=None):
        nickname = users.get_current_user().nickname()
        #submit_url = "/AddVehicle"
        if vid != None and vid != "":
            v = vehicle.Vehicle.get_by_id(int(vid))
            template_values = {
                               'nickname' : nickname,
                               'vehicle'  : v
                               }
            path = os.path.join(os.path.dirname(__file__), '../views/add_vehicle.html')
            self.response.out.write(template.render(path, template_values))
        else:
            template_values = {
                               'nickname' : nickname
                               }
            path = os.path.join(os.path.dirname(__file__), '../views/add_vehicle.html')
            self.response.out.write(template.render(path, template_values))

    def post(self, vid=None):
        name = self.request.get("name")
        make = self.request.get("make")
        model = self.request.get("model")
        year = self.request.get("year")
        color = self.request.get("color")
        plate = self.request.get("license_plate")

        if vid != None and vid != "":
            v = vehicle.Vehicle.get_by_id(int(vid))
            v.name = name
            v.model = model
            v.year = datetime.date(int(year), 1, 1)
            v.color = color
            v.license_plate = plate
        else:
            v = vehicle.Vehicle(name=name,
              make=make,
              model=model,
              year=datetime.date(int(year), 1, 1),
              color=color,
              license_plate=plate,
              license_plate_state="OR",
              owner=users.get_current_user())
        v.put()
        self.redirect("/home")
